<?php

/**
 * 素材管理
 */
namespace app\avikcm\controller;

use finfo;
use think\Db;
use think\facade\Request;

class Material extends Common
{
    public static $breadcrumb = [];
    public function initialize()
    {
        parent::initialize();
    }

    // 列表
    public function list(){
        $pid = input('pid', 0);
        if(Request::isAjax()){
            $key = input('post.key');
            $type = input('type', 0);
            $search = input('search', '');
            $this->assign('testkey', $key);
            $page = input('page', 1);
            $pageSize = input('limit', config('pageSize'));
            if($search != 'search'){
                $where[] = ['a.pid', '=', $pid];
            }
            $where[] = ['a.del','=',0];
            if ($key) {
                $where[] = ['a.title', 'like', "%" . $key . "%"];
            }
            if($type){
                $where[] = ['a.type','=',$type];
            }

            $paginate = ['list_rows'=>$pageSize,'page'=>$page];
            $list = db('material')->alias('a')->where($where)
                ->order('type')
                ->order('update_time', 'desc')->paginate($paginate)->toArray();
            if ($list['data']) {
                $file_type = config('file_type');
                foreach ($list['data'] as $key => $val) {
                    $list['data'][$key]['type_name'] = $file_type[$val['type']];
                }
            }

            return ['code'=>0,'msg'=>'成功','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        $this->getBreadcrumb($pid);
        $breadcrumb = self::$breadcrumb;
        ksort($breadcrumb);
        $this->assign('breadcrumb', $breadcrumb);
        $this->assign('file_type', config('file_type'));
        $this->assign('ptitle', '全部素材');
        $this->assign('pid', $pid);
        return $this->fetch();
    }

    // 添加文件
    public function add(){
        $pid = input('pid');
        if(Request::isAjax()){
            //构建数组
            $data = Request::except('file');
            $data['create_time'] = date("Y-m-d H:i:s",time());
            $data['update_time'] = date("Y-m-d H:i:s",time());
            $data['type'] = 1;
            db('material')->insert($data);
            $result['code'] = 1;
            $result['msg'] = '添加成功!';
            $result['url'] = url('list');
            return $result;
        }else{
            $ptitle = db('material')->where('id', $pid)->value('title');
            $this->assign('pid', $pid);
            $this->assign('ptitle', $ptitle);
            $this->assign('title', '上传文件');
            $this->assign('info','null');
            return $this->fetch();
        }
    }

    // 添加文件夹
    public function addDir(){
        $pid = input('pid');
        if(Request::isAjax()){
            //构建数组
            $data = Request::except('file');
            $data['create_time'] = date("Y-m-d H:i:s",time());
            $data['update_time'] = date("Y-m-d H:i:s",time());
            $data['type'] = 1;
            db('material')->insert($data);
            $result['code'] = 1;
            $result['msg'] = '添加成功!';
            $result['url'] = url('list');
            return $result;
        }else{
            $this->assign('pid', $pid);
            $this->assign('title', '新建文件夹');
            $this->assign('info','null');
            return $this->fetch();
        }
    }

    // 添加文件夹
    public function editDir()
    {
        $pid = input('pid');
        $id = input('id');
        if (Request::isAjax()) {
            //构建数组
            $data = Request::except('file');
            $data['update_time'] = date("Y-m-d H:i:s", time());
            db('material')->where('id', $id)->update($data);
            $result['code'] = 1;
            $result['msg'] = '修改成功!';
            $result['url'] = url('list');
            return $result;
        } else {
            $info = db('material')->where('id', $id)->find();
            $this->assign('pid', $pid);
            $this->assign('title', '重命名文件夹');
            $this->assign('info', json_encode($info));
            return $this->fetch('add_dir');
        }
    }

    // 预览文件
    public function preview()
    {
        $id = input('id');
        $info = db('material')->where('id', $id)->find();
        $this->assign('info', $info);
        return $this->fetch();
    }

    //上传
    public function uploads()
    {
        $pid = input('pid');
        $type = input('type', 3);
        
        // 获取表单上传文件
        $fileKey = array_keys(request()->file());
        $file = request()->file($fileKey['0']);
        
        // 移动到框架应用根目录/public/uploads/ 目录下
        $extStr = $this->getExt($type);
        $validate = $file->validate(['ext' => $extStr]);
        trace($validate, 'validate');
        $info = $validate->move('uploads');
        trace($info, 'move_info');
        if ($info) { 
            $fileInfo = $file->getInfo();
            trace($fileInfo, 'getinfo');
            $ext = $this->getFileExt($fileInfo['name']);
            trace($ext, 'file_ext');
            if(in_array($ext, ['jpg', 'png', 'jpeg'])){
                $type = 3;
            } elseif (in_array($ext, ['mp4', 'flv'])) {
                $type = 5;
            }
            $path = str_replace('\\', '/', $info->getSaveName());
            $data = [
                'pid'=>$pid,
                'title'=> $fileInfo['name'],
                'type'=> $type,
                'url' => '/uploads/' . $path,
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date("Y-m-d H:i:s"),
            ];
            $insert_id = db('material')->insertGetId($data);
            $result['code'] = 0;
            $result['msg'] = '上传成功!';
            $result["file"] = '/uploads/' . $path;
            $result['id'] = $insert_id;
            return $result;
        } else {
            // 上传失败获取错误信息
            $result['code'] = 1;
            $result['msg'] = '上传失败!';
            return $result;
        }
    }

    public function getExt($type)
    {
        switch ($type) {
            case '4':
                return 'jpg,png,jpeg';
                break;
            case '5':
                return 'mp4';
                break;
            default:
                return 'jpg,png,jpeg,pdf,doc,docx,xls,mp4';
                break;
        }
    }

    function getFileExt($file)
    {
        return end(explode(".",$file)); 
    } 

    // 删除新闻
    public function del(){
        $id = input('id');
        db('material')->where('id',$id)->update(['del'=>1]);
        return ['code'=>1,'msg'=>'删除成功！'];
    }

    // 批量删除新闻
    public function delAll(){
        $map[] =array('id','in',input('param.ids/a'));
        db('material')->where($map)->update(['del'=>1]);
        $result['msg'] = '删除成功！';
        $result['code'] = 1;
        return $result;
    }

    private function getBreadcrumb($pid, $data=''){
        
        if($pid > 0){
            $material = db('material')->field('id,pid,title')->where('id', $pid)->find();
            self::$breadcrumb[$material['id']] = $material;
            $this->getBreadcrumb($material['pid']);
        }
        else{
            self::$breadcrumb[0] = ['id' => 0, 'pid' => 0, 'title' => '全部素材'];
        }
    }

}